package com.javasea.patterns.strategy.factory.strategy;

import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.stream.Collectors;

/**
 * TODO 类功能介绍及重点或容易混淆点的说明。
 *
 * @version 1.0 2023/4/15 16:10 龙小南 新建类[说明]
 * @author: 龙小南
 * @Date: 2023/4/15 16:10
 * @Version 1.0[当前版本号]
 */

public class demo {

    public static void main(String[] args) {
        List<Student> list = List.of(new Student("1", "a1"), new Student("1", "b1"), new Student("3", "c1"));
        List<Student> students = removeRepeatStudentListByUserIdMethod3(list);
        System.out.println(students);
    }

    /**
     * 根据Student  userId去重 方法三
     *
     * @param studentList
     * @return
     */
    public static List<Student> removeRepeatStudentListByUserIdMethod3(List<Student> studentList) {
        if (studentList == null || studentList.size() <= 0) {
            return Collections.emptyList();
        }
        return studentList.stream().filter(distinctByKey(p -> p.getUserId())).collect(Collectors.toList());
    }


    public static <T> Predicate<T> distinctByKey(Function<? super T, Object> keyExtractor) {
        Map<Object, Boolean> map = new HashMap<>();
        return t -> {
            Boolean aBoolean = map.putIfAbsent(keyExtractor.apply(t), Boolean.TRUE);
            boolean b = aBoolean == null;
                    return b;
        };
    }
}
